package com.pri.chat.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.SettingInfo;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.rxjava.VersionBean;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.netease.nimlib.sdk.NIMClient;
import com.pri.chat.R;
import com.pri.chat.application.APP;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.base.TcWebActivity;
import com.pri.chat.model.SetModel;
import com.pri.chat.utils.Des3Util;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogJBSureCancel;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author
 * @time 2020/4/28
 */
public class SetActivity extends BaseActivity {

    @BindView(R.id.tv_edit)
    TextView tvEdit;
    @BindView(R.id.tv_verify_status_right)
    TextView tvVerifyStatusRight;
    @BindView(R.id.rl_real_verify)
    View rlRealVerify;
    @BindView(R.id.tv_jb_num)
    TextView tvJbNum;
    @BindView(R.id.ltsf_status)
    ImageView ltsf_status;

    @BindView(R.id.bing_mobile)
    View bing_mobile;
    @BindView(R.id.mobile_status)
    TextView mobile_status;



    @BindView(R.id.rl_chat)
    View rlChat;
    @BindView(R.id.rl_chat_line)
    View rl_chat_line;
    @BindView(R.id.tv_sm_num)
    TextView tvSmNum;
    @BindView(R.id.smtp_status)
    ImageView smtp_status;
    @BindView(R.id.rl_si)
    View rlSi;
    @BindView(R.id.rl_si_line)
    View rl_si_line;

    @BindView(R.id.gywm_linear)
    View gywm_linear;
    @BindView(R.id.yhxy_linear)
    View yhxy_linear;
    @BindView(R.id.yszc_linear)
    View yszc_linear;

    @BindView(R.id.version_linear)
    View version_linear;
    @BindView(R.id.tv_version)
    TextView tv_version;

    @BindView(R.id.yjfkLinear)
    View yjfkLinear;
    @BindView(R.id.zxzhLinear)
    View zxzhLinear;
    @BindView(R.id.ll_hmd)
    View ll_hmd;




    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_layout;
    }

    @Override
    protected void initView() {
        setTitle("设置");
        String version_num = getAPPVersionCode(this);
        tv_version.setText("V" + version_num);
    }

    /**
     * 获取版本号
     * @param ctx
     * @return
     */
    public static String getAPPVersionCode(Context ctx) {
        int currentVersionCode = 0;
        String appVersionName = "";
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
            System.out.println(currentVersionCode + " " + appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersionName;
    }


    private int ltsfStatus = 0;
    private int smtpStatus = 0;
    private String realPath = "";
    private String rzStatus = "";
    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
        if(SharedHelper.readMobile(this).isEmpty()){
            mobile_status.setText("未绑定");
        }else{
            mobile_status.setText(SharedHelper.readMobile(this));
        }
    }

    private SettingInfo sInfo;
    private void getData(){
        if (SharedHelper.readId(this).isEmpty()) {
            return;
        }
        if (!SharedHelper.readSex(this).equals("男")) {
            rlSi.setVisibility(View.VISIBLE);
            rl_si_line.setVisibility(View.VISIBLE);
            rlChat.setVisibility(View.VISIBLE);
            rl_chat_line.setVisibility(View.VISIBLE);
        } else {
            rlSi.setVisibility(View.GONE);
            rl_si_line.setVisibility(View.GONE);
            rlChat.setVisibility(View.GONE);
            rl_chat_line.setVisibility(View.GONE);
        }
        SubscriberOnNextListener<BaseBean<SettingInfo>> onNextListener = baseBean -> {
            sInfo= baseBean.getData();
            ltsfStatus = baseBean.getData().getTalkStatus();
            smtpStatus = baseBean.getData().getSmPictureStatus();
            tvSmNum.setText(baseBean.getData().getSmPictureGoldNumber() + "金币");
            tvJbNum.setText(baseBean.getData().getTalkGoldNumber() + "金币");
            ltsf_status.setImageResource(ltsfStatus==0?R.mipmap.ic_status_normal:R.mipmap.ic_status_select);
            smtp_status.setImageResource(smtpStatus==0?R.mipmap.ic_status_normal:R.mipmap.ic_status_select);
            if("0".equals(baseBean.getData().getRzStatus())){
                tvVerifyStatusRight.setText("待审核");
                tvVerifyStatusRight.setTextColor(getResources().getColor(R.color.color_333333));
            }else if("1".equals(baseBean.getData().getRzStatus())){
                tvVerifyStatusRight.setText("已认证");
                tvVerifyStatusRight.setTextColor(getResources().getColor(R.color.green));
            }else if("2".equals(baseBean.getData().getRzStatus())){
                tvVerifyStatusRight.setText("不通过");
                tvVerifyStatusRight.setTextColor(getResources().getColor(R.color.red));
            }else{
                tvVerifyStatusRight.setText("未认证");
                tvVerifyStatusRight.setTextColor(getResources().getColor(R.color.color_333333));
            }
            realPath = baseBean.getData().getRealPic();
            rzStatus = baseBean.getData().getRzStatus();
        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getSettingInfo(new ProgressSubscriber<>(onNextListener, this, false), requestBody);

    }

    RxDialogSureCancel rxDialogSureCancel;
    private void initRxDialog(String content,int status) {
        rxDialogSureCancel = new RxDialogSureCancel(this);
        rxDialogSureCancel.setTitle("提示信息");
        rxDialogSureCancel.setContent(content);
        rxDialogSureCancel.getSureView().setTextColor(getResources().getColor(R.color.orange));
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogSureCancel.dismiss();
            }
        });
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(status == 100){
                    zhuXiaoAccount();
                }else{
                    //請求接口
                    submitAdvice(status);
                }
                rxDialogSureCancel.dismiss();
            }
        });
        rxDialogSureCancel.show();
    }

    private int type = 0;
    private void submitAdvice(int status) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("设置成功");
            if (type == 0) {
                smtp_status.setImageResource(status==1?R.mipmap.ic_status_select:R.mipmap.ic_status_normal);
            } else {
                ltsf_status.setImageResource(status==1?R.mipmap.ic_status_select:R.mipmap.ic_status_normal);
            }
        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",SharedHelper.readId(this));
        params.put("type",type);
        params.put("status",status);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().updatePrice(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }


    private void zhuXiaoAccount() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("注销成功！");
            SharedHelper.clear(this);
            SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
            sp.edit().putBoolean("isFirst", true).apply();
            APP.getInstance().finishAllActivity();
            NimUIKit.logout();
            RxActivityTool.skipActivity(mContext,LoginActivity.class);
        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().zhuXiaoAccount(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    @OnClick({R.id.ll_hmd,R.id.yjfkLinear,R.id.zxzhLinear,R.id.version_linear,R.id.bing_mobile,R.id.yhxy_linear, R.id.yszc_linear, R.id.ltsf_status,R.id.smtp_status,R.id.gywm_linear, R.id.tv_edit, R.id.rl_real_verify})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.ll_hmd:
                RxActivityTool.skipActivity(mContext, HeiMingDanMemberActivity.class);
                break;
            case R.id.bing_mobile:
                if(SharedHelper.readMobile(this).isEmpty()){
                    RxActivityTool.skipActivity(this,BindMobieActivity.class);
                }else{
                    RxToast.normal("您已经绑定过手机号！");
                }
                break;
            case R.id.ltsf_status:
                type = 1;
                if(ltsfStatus==0){
                    initRxDialog("您确定打开聊天收费设置？",1);
                }else{
                    initRxDialog("您确定关闭聊天收费设置？",0);
                }
                break;
            case R.id.smtp_status:
                type = 0;
                if(smtpStatus==0){
                    initRxDialog("您确定打开私密照片收费设置？",1);
                }else{
                    initRxDialog("您确定关闭私密照片收费设置？",0);
                }
                break;
            case R.id.tv_edit:
                SharedHelper.clear(this);
                SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                sp.edit().putBoolean("isFirst", true).apply();
                NimUIKit.logout();
                APP.getInstance().finishAllActivity();
                RxActivityTool.skipActivity(mContext,LoginActivity.class);
                finish();
                break;
            case R.id.rl_real_verify:
                if("0".equals(sInfo.getRzStatus())){
                    RxToast.normal("审核中，请耐心等待...");
                }else if("1".equals(sInfo.getRzStatus())){
                    RxToast.normal("已认证，不能重复认证！");
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putString("rzStatus",rzStatus);
                    bundle.putString("realPath",realPath);
                    RxActivityTool.skipActivity(this, RealVerifyActivity.class,bundle);
                }
                break;
            case R.id.yhxy_linear:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title","用户协议");
                intent.putExtra("url", HttpMethods.BASE_URL+"p/front_editorHtmlShow.html?code=yonghuxieyiCode");
                startActivity(intent);
                break;
            case R.id.yszc_linear:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title","隐私协议");
                intent.putExtra("url", HttpMethods.BASE_URL+"p/front_editorHtmlShow.html?code=yinsixieyiCode");
                startActivity(intent);
                break;
            case R.id.gywm_linear:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title","关于我们");
                intent.putExtra("url", HttpMethods.BASE_URL+"p/front_editorHtmlShow.html?type=2");
                startActivity(intent);
                break;
            case R.id.version_linear:
                getVersion();
                break;
            case R.id.yjfkLinear:
                initRxDialog();
                break;
            case R.id.zxzhLinear:
                type = 2;
                initRxDialog("确定要注销此账号？",100);
                break;
        }
    }


    private void getVersion() {
        SubscriberOnNextListener<BaseBean<VersionBean>> onNextListener = baseBean -> {
            if (baseBean.getData().getVersion().equals("v"+getAPPVersionCode(this))) {
                RxToast.normal("已是最新版本！");
                return;
            }
            showTipDialog(activity, baseBean.getData().getApkPath());
        };
        HttpMethods.getInstance().getVersionInfo(new ProgressSubscriber<>(onNextListener, this, false));
    }

    private AlertDialog mUpdateAlert;
    private AlertDialog.Builder mUpdateBuidler;
    /**
     * 更新应用弹窗
     *
     * @param activity 上下文
     * @param s        提示文字
     */
    public void showTipDialog(Activity activity, String s) {
        mUpdateAlert = null;
        mUpdateBuidler = new AlertDialog.Builder(activity);
        mUpdateAlert = mUpdateBuidler
                .setTitle(R.string.main_tip)
                .setMessage(R.string.jump_app_store)
                .setCancelable(false)
                .setPositiveButton(R.string.confirm, (dialog, which) -> openBrowser(activity, s))
                .create();             //创建AlertDialog对象
        mUpdateAlert.show();                    //显示对话框
    }

    /**
     * 打开浏览器
     *
     * @param context 上下文
     * @param url     链接
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, context.getString(R.string.choice_browser)));
        } else {
            RxToast.normal("链接错误或无浏览器");
        }
    }



    RxDialogJBSureCancel rxDialogEditSureCancel;
    private void initRxDialog() {
        rxDialogEditSureCancel = new RxDialogJBSureCancel(this);
        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
            }
        });
        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = rxDialogEditSureCancel.getEditText().getText().toString();
                if(StringUtil.isEmpty(content)){
                    RxToast.normal("请输入您的建议！");
                    return;
                }
                submitAdvice(content);
                rxDialogEditSureCancel.dismiss();
            }
        });
        rxDialogEditSureCancel.show();
    }
    private void submitAdvice(String content) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("提交成功！");
        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(this));
        params.put("content", content);
        Gson gson = new Gson();
        String s = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().submitAdvice(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
